# -*- coding:utf-8 -*-
"""

@author: liandyao
@date: 2025/1/16 16:30
"""
import datetime
import os
import random
import time

from PIL import Image, ImageDraw, ImageFont

import subprocess

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time


# 使用合适的中文字体，例如微软雅黑或黑体
from video_jian import add_video_cover

font_path = r'msyhbd.ttc'

tags=["#动画电影",
     "#经典动漫",
      "#宫崎骏动漫",
      "#宫崎骏动漫",
      "#爱本身没有那么复杂",
    "#寒假快乐图鉴"]
class AutoRelease:
    def __init__(self, titles,  descris,tags=tags):
        # 初始化参数并将其存储为实例变量
        self.titles = titles  # 文字标题列表
        self.descris = descris  # 描述
        self.tags = tags  # 标签

    # 快手发布
    '''
    video_path 表示视频的路径
    title 表示需要写在封面的标题
    account_en 是账号的英文名称或者数字,不要使用中文
    '''
    def auto_release_kuaishou(self,video_path,title,account_en):
        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        try:
            driver.get("https://cp.kuaishou.com/article/publish/video")
        except Exception as e:
            print(f"Failed to load page: {e}")

        time.sleep(30)
        print('开始上传视频.')
        # 视频上传
        file_input = WebDriverWait(driver, 600).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))

        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(3)
        try:
            # 等待第三个按钮出现  -- 第三个是合集
            button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.XPATH,
                     "(//div[contains(@class, 'ant-select ant-select-single ant-select-allow-clear ant-select-show-arrow')])[4]")
                )
            )

            print("找到按钮，准备点击。")

            # 点击按钮
            button.click()
            print("合集按钮已被点击。")

            time.sleep(3)
            # 等待并找到第一个具有 ant-select-item-option 类的 div 元素
            first_item = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ant-select-item-option"))
            )

            # 点击该元素
            first_item.click()
            print("已点击活跃选项。")
        except Exception as e:
            print(f"快手发布Error: {e}")

        random_title=''
        # 随机选择一个标题
        if len(self.titles) > 0:
            random_title = random.choice(self.titles)
        print(random_title)
        time.sleep(3)
        descri = random.choice(self.descris)
        # 填写描述
        title_input = WebDriverWait(driver, 150).until(
            EC.element_to_be_clickable((By.ID, "work-description-edit")))
        title_input.send_keys(f"{title} {random_title} {descri} ")
        # 每次加三个标签
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")
        time.sleep(2)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")
        time.sleep(1)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")

        # 等待直到特定类名的元素出现-当有预览按钮时,说明上传成功
        preview_header = WebDriverWait(driver, 240).until(
            EC.presence_of_element_located((By.CLASS_NAME, "_preview-header_1ahzu_92"))
        )
        print("找到元素，继续执行下一步。")

        # 发布
        time.sleep(3)
        # 等待并找到具有特定类名并包含"发布"文本的 div 元素
        publish_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH,
                                        "//div[contains(@class, '_button_si04s_1') and contains(@class, '_button-primary_si04s_60')]//div[text()='发布']"))
        )

        # 点击该元素
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)


        driver.quit()  # 确保在完成后关闭浏览器


    def auto_release_douyin(self,video_path,title,account_en):

        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        '''
             作用：发布抖音视频
            '''

        # 进入创作者页面，并上传视频
        driver.get("https://creator.douyin.com/creator-micro/content/upload")
        time.sleep(10)
        # 视频上传
        file_input = WebDriverWait(driver, 600).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))

        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(10)

        try:
            # 点击封面
            cover_button = WebDriverWait(driver, 600).until(
                EC.element_to_be_clickable((By.XPATH, "//div[@class='cover-Jg3T4p']"))
            )
            cover_button.click()
            time.sleep(2)
            # 点击竖版按钮
            shuban_btn = WebDriverWait(driver, 600).until(
                EC.element_to_be_clickable((By.XPATH, "//button[@class='semi-button semi-button-primary semi-button-light primary-RstHX_']"))
            )
            shuban_btn.click()
            # 点击完成按钮
            time.sleep(2)
            wancheng_btn = WebDriverWait(driver, 600).until(
                EC.element_to_be_clickable((By.XPATH, "//button[@class='semi-button semi-button-primary semi-button-light primary-RstHX_']"))
            )
            wancheng_btn.click()

        except Exception as e:
            print(f"点击抖音封面Error: {e}")

        time.sleep(3)
        # 等待输入框加载并获取元素
        input_element = WebDriverWait(driver, 600).until(
            EC.visibility_of_element_located((By.XPATH, "//input[@class='semi-input semi-input-default' and @type='text']"))
        )


        # 随机选择一个标题
        random_title = random.choice(self.titles)
        print(random_title)

        input_element.send_keys(f"{title} ")  # 替换为你要设置的文本
        input_element.send_keys(f'{random_title}')
        time.sleep(2)
        # 等待加载 input 元素  标题
        input_element2 = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'editor-kit-container'))
        )
        time.sleep(2)
        # 随机选择一个标题
        random_desc = random.choice(self.descris)
        print(random_desc)


        # 设置文本
        input_element2.send_keys(f"{random_desc} ")  # 替换为你要设置的文本
        input_element2.send_keys(f"{random.choice(self.tags)} ")
        input_element2.send_keys(f"{random.choice(self.tags)} ")
        input_element2.send_keys(f"{random.choice(self.tags)} ")

        time.sleep(2)

        # 加入活动标识
        try:
            # 等待目标类似结构的 div 元素及其包含“动画”文本的下级 div 加载
            target_element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (
                        By.XPATH,
                        "//div[contains(@class, 'container-BPqaWp activity-right-N1pBMo')]//div[descendant::text()[contains(., '动画')]]"
                    )
                )
            )

            # 点击该元素
            target_element.click()
            time.sleep(2)
        except Exception as e:
            print(f"没有相关活动：{e}")

        try:
            # 加入合集
            # 等待并点击第一个下拉框的 div semi-select select-collection-VQbX7A semi-select-single
            select_div = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.CLASS_NAME, "semi-select.select-collection-VQbX7A")
                )
            )
            select_div.click()  # 点击下拉选择框
            time.sleep(1)
            # 第1个合集,索引从1开始
            index = 1
            # 等待下拉选项出现，并找到第一个选项并点击
            first_option = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.XPATH, "(//div[contains(@class, 'semi-select-option collection-option')])[" + str(index) + "]")
                )
            )

            first_option.click()
            print('成功点击合集')


        except Exception as e:
            print(f"未找到目标元素，错误信息：{e}")

        time.sleep(20)
        try:
            # 等待并检查是否存在包含"重新上传"文本的 div
            upload_div = WebDriverWait(driver, 180).until(
                EC.visibility_of_element_located(
                    (By.XPATH, "//div[contains(text(), '重新上传')]")  # 使用 XPath 来查找包含文本的 div
                )
            )
        except Exception as e:
            print(f"未找到目标元素，错误信息：{e}")

        # 如果找到了 upload_div，则输出成功信息
        print("上传成功！可以点击发布按钮。")

        # 滚动到底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(4)  # 等待滚动完成


        publish_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 "//button[contains(@class, 'primary-cECiOJ')]")
            )
        )



        # 点击发布按钮
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)

        driver.quit()  # 确保在完成后关闭浏览器


# 截取视频
def clip_video(input_video_path, output_video_path, start_time,end_time):
    """
    使用 ffmpeg 剪辑视频
    :param input_video_path: 输入视频文件路径
    :param output_video_path: 输出视频文件路径
    :param start_time: 剪辑开始时间，格式为 "HH:MM:SS" 或 "秒数"
    """
    # 将 start_time 转换为秒数
    if isinstance(start_time, str):
        # 如果是 HH:MM:SS 格式
        time_parts = start_time.split(':')
        if len(time_parts) == 3:  # HH:MM:SS
            start_seconds = int(time_parts[0]) * 3600 + int(time_parts[1]) * 60 + int(time_parts[2])
        elif len(time_parts) == 2:  # MM:SS
            start_seconds = int(time_parts[0]) * 60 + int(time_parts[1])
        else:  # 仅为秒数
            start_seconds = int(time_parts[0])
    else:
        start_seconds = int(start_time)  # 如果是直接以秒数给出



    # 确保持续时间不为负数
    if end_time <= 0:
        raise ValueError("剪辑的开始时间超出了视频的总时长。")

    command = [
        'ffmpeg',
        '-i', input_video_path,
        '-ss', str(start_seconds),  # 开始时间
        '-t', str(end_time),  # 持续时间
        '-c:v', 'libx264',  # 使用 libx264 编码视频
        '-preset', 'ultrafast',  # 设置编码速度
        '-crf', '23',  # 控制质量
        '-c:a', 'aac',  # 使用 AAC 编码音频
        '-vf', 'scale=iw*0.5:ih*0.5',  # 缩小到原始分辨率的 0.5 倍
        output_video_path
    ]

    print("执行剪切命令:", command)  # 调试打印
    subprocess.run(command, check=True, encoding='utf-8')
    print('视频地址',output_video_path)

def main():
    # # 获取当前脚本的绝对路径
    current_script_path = os.path.abspath(__file__)
    print(f"当前脚本的绝对路径是: {current_script_path}")

    # 获取当前脚本所在的目录
    current_script_dir = os.path.dirname(current_script_path)
    print(f"当前脚本所在的目录是: {current_script_dir}")
    #
    titles = [
        "经典儿童电影！",
        "想象力打开",
        "永远的童年快乐",
        "宫崎骏动漫",
    ]

    descris = [
        '宫崎骏打开方式','童年的快乐时光', '快乐整个寒假', '来看电影吧', '动画电影'
    ]
    # # 初始化自动发布对象
    auto = AutoRelease(titles=titles, descris=descris)
    #
    video_path = 'G:\\BaiduNetdiskDownload\\少儿英语动画全集分级\\'
    file_name = '2013-起风了【国语】.mkv'
    title = '起风了'
    video_duration = add_video_cover.get_video_duration(video_path + file_name)
    print(f"视频时长为：{video_duration} 秒")

    segment_duration = video_duration / 5
    # 截取 段视频
    for i in range(3):
        start_time = i * segment_duration
        if start_time ==0 :
            start_time = 20 # 跳过前面几秒的广告
        end_time = segment_duration
        print(f"截取视频片段 {i + 1}：{start_time} 秒 - {end_time} 秒")
        output_video_path = f"{current_script_dir}\\{title}_{i + 1}.mp4"
        clip_video(video_path+file_name, output_video_path, start_time, end_time)
        out=add_video_cover.start(output_video_path,title+'_'+str(i+1))

        print('已完成加封面',current_script_dir+'\\'+out)
        auto.auto_release_kuaishou(video_path=out, title=title+'_'+str(i+1), account_en='User_Data_ks_anxinshuijiao')
        auto.auto_release_kuaishou(video_path=out, title=title+'_'+str(i+1), account_en='User_Data')
        #auto.auto_release_douyin(video_path=out, title=title+'_'+str(i+1), account_en='User_Data')
        #auto.auto_release_douyin(video_path=out, title=title+'_'+str(i+1), account_en='User_Data_Qinggan')

if __name__ == '__main__':

    main()
    # titles = [
    #     "经典儿童电影！",
    #     "想象力打开",
    #     "永远的童年快乐"
    # ]
    #
    # descris = [
    #     '童年的快乐时光', '快乐整个寒假', '来看电影吧', '动画电影'
    # ]
    # # # 初始化自动发布对象
    # auto = AutoRelease(titles=titles, descris=descris)
    # out=r'D:\liandyao\01work\pythonProject\pythonProject2\video_jian\天才眼镜狗_4_1.mp4'
    # i=0
    # # # #auto.auto_release_kuaishou(video_path=out, title=title + '_' + str(i + 1), account_en='User_Data')
    # # # #auto.auto_release_douyin(video_path=out, title=title + '_' + str(i + 1), account_en='User_Data')
    # auto.auto_release_douyin(video_path=out, title='天才眼镜狗_4', account_en='User_Data_Qinggan')